package cn.jinjimi.app.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.domain.data.dto.ArticleListDTO;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.store.ReaderStore;
import cn.jinjimi.app.entity.Article;
import cn.jinjimi.app.main.adapter.ArticleSearchAdapter;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.widget.XListView.XListView;

import java.util.List;
import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by lforxeverc on 2017/2/4.
 */

public class ArticleSearchActivity extends BaseActivity implements View.OnClickListener, XListView.IXListViewListener {
    private TextView tvTips, tvSearchResultTips;
    private EditText etSearch;
    private ImageView ivClear;

    private XListView mListView;
    private ArticleSearchAdapter mAdapter;

    private static final int MESSAGE_SEARCH = 1;
    private int page = Constants.DEFAULT_PAGE;
    private int AUTO_SEARCH_DURATION = 1000;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_article_search);
    }

    @Override
    protected void initial() {
        tvTips = (TextView) findViewById(R.id.tv_tips);
        tvSearchResultTips = (TextView) findViewById(R.id.tv_search_result);
        etSearch = (EditText) findViewById(R.id.et_search);
        ivClear = (ImageView) findViewById(R.id.iv_clear);
        mListView = (XListView) findViewById(R.id.lv_result);

        findViewById(R.id.tv_cancel).setOnClickListener(this);
        ivClear.setOnClickListener(this);
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        mListView.setXListViewListener(this);
        mListView.setEnablePullEmpty(false);

        mAdapter = new ArticleSearchAdapter(this);
        mListView.setAdapter(mAdapter);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String result = s.toString().trim();
                sendSearchMessage(result, Constants.DEFAULT_PAGE, AUTO_SEARCH_DURATION, false);

            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    sendSearchMessage(v.getText().toString(), Constants.DEFAULT_PAGE, 0, false);
                }
                return false;
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Article article = mAdapter.getItem(position - mListView.getHeaderViewsCount());
                //打开文章页面
                Intent intent = new Intent(ArticleSearchActivity.this, ReaderDetailActivity.class);
                intent.putExtra(BundleKey.ARTICLE_ID, article.getId());
                intent.putExtra(BundleKey.ARTICLE_LINK, article.getLink());
                startActivity(intent);
            }
        });

        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    AndroidUtils.hideSoftKeyBoard(ArticleSearchActivity.this, etSearch);
                }
                return false;
            }
        });
    }

    private void sendSearchMessage(String key, int page, int delay, boolean ignoreInputEt) {
        String title = key;
        ivClear.setVisibility(title.isEmpty() ? View.GONE : View.VISIBLE);
        if (TextUtils.isEmpty(title)) return;
        mHandler.removeMessages(MESSAGE_SEARCH);

        Message msg = Message.obtain();
        msg.what = MESSAGE_SEARCH;
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putInt("page", page);
        bundle.putBoolean("ignoreInput", ignoreInputEt);
        msg.setData(bundle);
        mHandler.sendMessageDelayed(msg, delay);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what != MESSAGE_SEARCH || etSearch == null || isFinishing()) return;
            Bundle bundle = msg.getData();
            String msgKey = bundle.getString("title");
            boolean ignoreInput = bundle.getBoolean("ignoreInput");
            int page = bundle.getInt("page");
            String etInput = etSearch.getText().toString();
            if (ignoreInput || etInput.equals(msgKey)) {
                search(msgKey, page, ignoreInput);
            }

        }
    };

    private void search(final String title, final int spage, final boolean ignoreInput) {
        Task.callInBackground(new Callable<ArticleListDTO>() {
            @Override
            public ArticleListDTO call() throws Exception {
                return ServiceManager.getService(ReaderStore.class).searchArticles(title, spage, Constants.PAGE_LIMIT_10);
            }
        }).continueWith(new Continuation<ArticleListDTO, Void>() {
            @Override
            public Void then(Task<ArticleListDTO> task) throws Exception {
                mListView.stopRefresh();
                mListView.stopLoadMore();
                ArticleListDTO result = task.getResult();
                String input = etSearch.getText().toString();
                if (!title.equals(input) && !ignoreInput) return null;
                if (result != null && result.isOk) {
                    List<Article> mData = result.getArticles();
                    if (mData != null && !mData.isEmpty()) {
                        if (spage == Constants.DEFAULT_PAGE) {
                            page = Constants.DEFAULT_PAGE;
                            tvTips.setVisibility(View.VISIBLE);
                            tvTips.setText(String.format(getString(R.string.article_search_tips), title));
                            tvSearchResultTips.setVisibility(View.GONE);
                            mListView.setVisibility(View.VISIBLE);
                            mAdapter.setMatchText(title);
                            mAdapter.setItems(mData);
                            mListView.smoothScrollToPosition(0);
                        } else {
                            page++;
                            mAdapter.addItems(mData);
                        }
                    } else {
                        if (spage == Constants.DEFAULT_PAGE) {
                            tvTips.setVisibility(View.GONE);
                            tvSearchResultTips.setVisibility(View.VISIBLE);
                            tvSearchResultTips.setText(getString(R.string.search_result_empty));
                            mListView.setVisibility(View.GONE);
                        }
                    }
                    mListView.setPullLoadEnable(!(mData == null || mData.size() < Constants.PAGE_LIMIT_10));
                } else {
                    ToastUtils.toastMessage(ArticleSearchActivity.this, getString(R.string.article_search_fail));
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.iv_clear:
                etSearch.setText("");
                break;
        }
    }

    @Override
    public void onRefresh() {
    }

    @Override
    public void onLoadMore() {
        sendSearchMessage(mAdapter.getMatchText(), page + 1, 0, true);
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeMessages(MESSAGE_SEARCH);
            mHandler = null;
        }
        super.onDestroy();
    }
}
